from typing import List
from .model import Reasoncode
from ninja import Field, ModelSchema, Query, Router
from ninja.pagination import paginate
from utils.fu_crud import (
    ImportSchema,
    create,
    delete,
    export_data,
    import_data,
    retrieve,
    update,
)
from utils.fu_ninja import FuFilters, MyPagination

router = Router()


# 设置过滤字段
class Filters(FuFilters):
        
    name: str = Field(None, alias='name')    
    reason_code: str = Field(None, alias='reason_code')


# 设置请求接收字段
class ReasoncodeSchemaIn(ModelSchema):

    class Config:
        model = Reasoncode
        model_exclude = ['create_datetime', 'update_datetime', 'belong_dept', 'modifier', 'creator', 'id']


# 设置响应字段
class ReasoncodeSchemaOut(ModelSchema):

    class Config:
        model = Reasoncode
        model_fields = '__all__'


# 创建Reasoncode
@router.post('/reasoncode', response=ReasoncodeSchemaOut)
def create_reasoncode(request, data: ReasoncodeSchemaIn):
    reasoncode = create(request, data, Reasoncode)
    return reasoncode


# 删除Reasoncode
@router.delete('/reasoncode/{id}')
def delete_reasoncode(request, id: int):
    delete(id, Reasoncode)
    return {'success': True}


# 更新Reasoncode
@router.put('/reasoncode/{id}', response=ReasoncodeSchemaOut)
def update_reasoncode(request, id: int, data: ReasoncodeSchemaIn):
    reasoncode = update(request, id, data, Reasoncode)
    return reasoncode


# 获取Reasoncode
@router.get('/reasoncode', response=List[ReasoncodeSchemaOut])
@paginate(MyPagination)
def list_reasoncode(request, filters: Filters = Query(...)):
    qs = retrieve(request, Reasoncode, filters)
    return qs


# 导入
@router.get('/reasoncode/all/export')
def export_reasoncode(request):
    export_fields = ('name', 'reason_code', )
    return export_data(request, Reasoncode, ReasoncodeSchemaOut, export_fields)


# 导出
@router.post('/reasoncode/all/import')
def import_reasoncode(request, data: ImportSchema):
    import_fields = ('name', 'reason_code', )
    return import_data(request, Reasoncode, ReasoncodeSchemaIn, data, import_fields)
    